package middle;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution_473 {

    public static boolean makesquare(int[] nums) {
        Arrays.sort(nums);
        int sum = 0;
        for (int num : nums) {
            sum+=num;
        }
        if (sum%4!=0) return false;
        int l = sum/4;
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < 4; i++) {
            if (!isFind(nums, set, l)) {
                return false;
            }
        }
        return true;
        /*
        for (int i = nums.length-1;i>=0;i--) {
            int cha = l-nums[i];
            Integer count = map.get(nums[i]);
            if (cha==0) {
                map.put(nums[i], count--);
            } else if (cha<0){
                return false;
            } else {
                if (!map.containsKey(cha)) {
                    return false;
                } else if((chaCount=map.get(cha))>0) {
                    map.put(nums[i], count--);
                    map.put(cha, chaCount--);
                }
            }
        }*/
//        return true;
    }

    /**
     * 判断是否能组成目标值
     * @param nums
     * @param target
     * @return
     */
    private static boolean isFind(int[] nums, Set<Integer> set, int target) {
        for (int i = nums.length-1; i >= 0; i--) {
            if (set.contains(i) || nums[i]>target) {
                continue;
            } else if (nums[i]==target) {
                set.add(i);
                return true;
            } else {
                set.add(i);
                boolean find = isFind(nums, set, target - nums[i]);
                if (find) {
                    return true;
                } else {
                    set.remove(i);
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
//        System.out.println(makesquare(new int[]{1,1,1,1}));
//        System.out.println(makesquare(new int[]{1,1,2,2,2}));
//        System.out.println(makesquare(new int[]{3,3,3,3,4}));
//        System.out.println(makesquare(new int[]{2,2,2,2,2,3,5,9,9}));
    }
}
